package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.feign.BehaviorFeign;
import com.heima.search.mapper.ApUserSearchMapper;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2021/2/22 14:12
 **/
@Service
@Slf4j
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService {
    @Autowired
    BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {
        log.info("findUserSearch 查询历史记录 ==>{}",userSearchDto);
        // 1. 检查参数
        if(userSearchDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 获取行为实体ID
        ApBehaviorEntry entry = getEntry(userSearchDto);
        if(entry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"行为实体不存在");
        }
        // 3. 查询搜索历史记录列表
        IPage<ApUserSearch> pageRequest = new Page(0,5);
        IPage<ApUserSearch> pageResult = page(pageRequest, Wrappers.<ApUserSearch>lambdaQuery()
                .eq(ApUserSearch::getEntryId, entry.getId())
                .eq(ApUserSearch::getStatus, 1)
                .orderByDesc(ApUserSearch::getCreatedTime)
        );
        return ResponseResult.okResult(pageResult.getRecords());
    }
    @Override
    public ResponseResult delUserSearch(UserSearchDto userSearchDto) {
        log.info("delUserSearch 删除历史记录 ==>{}",userSearchDto);
        //1. 检查参数
        if(userSearchDto == null || userSearchDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 根据id查询该历史记录
        ApUserSearch userSearch = getById(userSearchDto.getId());
        //3. 将历史记录的status修改为0
        if(userSearch == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        userSearch.setStatus(0); // 失效状态
        updateById(userSearch);
        return ResponseResult.okResult();
    }

    @Override
    @Async // 当前方法会被 异步执行 (spring会利用线程池来执行这个方法)
    public void insert(Integer entryId, String searchWords) {
        // 1. 根据行为实体ID 及 关键词查询历史记录中是否已经存在
        ApUserSearch userSearch = getOne(
                Wrappers.<ApUserSearch>lambdaQuery()
                        .eq(ApUserSearch::getEntryId, entryId)
                        .eq(ApUserSearch::getKeyword, searchWords)
        );
        // 2. 如果存在 将记录的状态status改为1 (激活状态)
        if(userSearch!=null){
            userSearch.setStatus(1);
            userSearch.setCreatedTime(new Date());
            updateById(userSearch);
        }else {
            // 3. 如果不存在  保存历史记录
            userSearch = new ApUserSearch();
            userSearch.setEntryId(entryId);
            userSearch.setKeyword(searchWords);
            userSearch.setStatus(1); // 激活
            userSearch.setCreatedTime(new Date());
            save(userSearch);
        }
    }

    private ApBehaviorEntry getEntry(UserSearchDto userSearchDto) {
        ApUser user = AppThreadLocalUtils.getUser();
        return behaviorFeign.findByUserIdOrEntryId(user==null? 0 : user.getId() , userSearchDto.getEquipmentId());
    }
}
